// handlers/BaseHandler.js
const fs = require('fs');
const mime = require('mime-types');

class BaseHandler {
    constructor(server) {
        this.server = server;
    }
    async handle(req, res, filePath) {
        throw new Error('handle method must be implemented by subclass');
    }

    async fileExists(filePath) {
        try {
            await fs.promises.access(filePath);
            return true;
        } catch {
            return false;
        }
    }

    getMimeType(filePath) {
        return mime.lookup(filePath) || 'application/octet-stream';
    }

    // 生成安全的文件名
    sanitizeFileName(name) {
        return name.replace(/[^a-zA-Z0-9\u4e00-\u9fa5\-_.]/g, '_');
    }

    // 发送错误响应
    sendError(res, statusCode, message) {
        res.status(statusCode).json({
            error: message,
            timestamp: new Date().toISOString()
        });
    }
}

module.exports = BaseHandler;